﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SQLTouch.Service.DataContracts;

namespace SQLTouch.Client.Metro.ViewModel.Home
{
    public class AddDatabaseVM : VMBase
    {
        private readonly IFacade facade;
        private readonly IPopupService popup;
        private string connectionString;
        private string connectionStringErrors;
        private readonly RelayCommand add;
        private readonly RelayCommand cancel;

        public AddDatabaseVM(IFacade facade, IPopupService popup)
        {
            this.facade = facade;
            this.popup = popup;
            this.add = new RelayCommand(DoAdd, CanAdd);
            this.cancel = new RelayCommand(DoCancel);
        }

        public string ConnectionString
        {
            get { return connectionString; }
            set
            {
                if (connectionString != value)
                {
                    connectionString = value;
                    RaisePropertyChanged("ConnectionString");
                    add.RaiseCanExecuteChanged();
                }
            }
        }

        public string ConnectionStringErrors
        {
            get { return connectionStringErrors; }
            private set
            {
                if (connectionStringErrors != value)
                {
                    connectionStringErrors = value;
                    RaisePropertyChanged("ConnectionStringErrors");
                }
            }
        }

        public RelayCommand Add
        {
            get { return add; }
        }

        public RelayCommand Cancel
        {
            get { return cancel; }
        }

        private void RefreshErrors()
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                ConnectionStringErrors = "Please enter a connection string.";
            }
            else
            {
                ConnectionStringErrors = string.Empty;
            }
        }

        private bool CanAdd()
        {
            return !string.IsNullOrWhiteSpace(connectionString);
        }

        private void DoAdd()
        {
            try
            {
                facade.AddDatabase(new DatabaseData(Guid.NewGuid(), connectionString));
            }
            catch (Exception ex)
            {
                facade.ShowUnexpectedError("Unable to add the database.", ex);
                return;
            }
            popup.ClosePopup();
        }

        private void DoCancel()
        {
            popup.ClosePopup();
        }
    }
}
